package controller;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.PaperLog;
import core.PgSQL;
import core.Tool;
import core.View;

public class RankList extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static PgSQL db = PgSQL.getInstance();

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		
		int limit = 20;
		int page = Math.max(1, Tool.intval(request.getParameter("page")));
		int offset = (page - 1) * limit;

		String condition = "";
		LinkedList<PaperLog> paperlogs = new LinkedList<PaperLog>();

		int pid = Tool.intval(request.getParameter("pid"));
		if(pid > 0){
			condition = " WHERE l.pid=" + pid;
		}

		ResultSet rs = db.query("SELECT p.*,l.uid,u.username,l.score,l.dateline FROM qz_paperlog l LEFT JOIN qz_paper p ON p.pid=l.pid LEFT JOIN qz_user u ON u.uid=l.uid " + condition + " ORDER BY l.score DESC OFFSET " + offset + " LIMIT " + limit);
		try{
			while(rs.next()){
				paperlogs.add(PaperLog.fromDatabase(rs));
			}
		}catch(SQLException e){
			e.printStackTrace();
		}
		
		int totalnum = 0;
		rs = db.query("SELECT COUNT(*) FROM qz_paperlog");
		try{
			if(rs.next()){
				totalnum = rs.getInt(1);
			}
		}catch(SQLException e){
			e.printStackTrace();
		}
		
		request.setAttribute("paperlog[]", paperlogs.toArray(new PaperLog[0]));
		request.setAttribute("limit", limit);
		request.setAttribute("page", page);
		request.setAttribute("totalnum", totalnum);
		
		View.show(request, response, "ranklist");
	}
}
